import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import { createRequire } from 'module';
import path, { dirname, resolve } from 'path';
import { fileURLToPath } from 'url';
import { loadEnv, mergeConfig } from 'vite';
import svgLoader from 'vite-svg-loader';
import plugins from './plugins.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const require = createRequire(import.meta.url);

export default async ({ command, mode, ssrBuild }, other) => {
  const isBuild = command === 'build';
  const isServe = command === 'serve';
  const isSite = mode.includes('site');
  const envDir = path.resolve(__dirname, 'env');
  const env = loadEnv(mode, envDir, '');

  let o = {
    mode: mode,
    envPrefix: 'TELD_',
    base: './',
    plugins: [
      vue(),
      vueJsx({}),
      svgLoader({ svgoConfig: {} }),
      ...(await plugins({
        ...other,
      })),
    ],
    resolve: {
      alias: [
        { find: 'src', replacement: resolve(process.cwd(), 'src') },
        { find: 't', replacement: resolve(process.cwd(), 'components') },
        {
          find: 'components',
          replacement: resolve(process.cwd(), 'components'),
        },
      ],
      extensions: ['.mjs', '.js', '.jsx', '.ts', '.tsx', '.vue'],
    },
    define: {
      'process.env': {},
      '__TIME__': JSON.stringify(new Date().toLocaleString()),
      '__VERSION__': JSON.stringify(process.env.npm_package_version),
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `$xxx: orange;`,
        },
        less: {
          // modifyVars: {
          //   hack: `true; @import (reference) "${resolve(
          //     'src/assets/style/breakpoint.less'
          //   )}";`,
          // },
          javascriptEnabled: true,
        },
      },
    },
    // experimental: {
    //   renderBuiltUrl(filename, { hostType, type, ssr }) {
    //     if (ssr && type === 'asset' && hostType === 'js') {
    //       return {
    //         runtime: `__ssr_vue_processAssetPath(${JSON.stringify(filename)})`,
    //       }
    //     }
    //   },
    // },
    // ssr: {
    //   noExternal: [
    //     '@vitejs/test-example-external-component',
    //   ],
    // },
    // optimizeDeps: {
    //   exclude: ['@vitejs/test-example-external-component'],
    // },
    build: {
      emptyOutDir: true,
      cssCodeSplit: true,
      assetsInlineLimit: 0,
      rollupOptions: {
        output: {
          chunkFileNames(v) {
            return 'chunk/[hash].js';
          },
          assetFileNames: assetInfo => {
            if (assetInfo.name.endsWith('.css')) {
              return 'style.css';
            }
            return assetInfo.name;
          },
        },
      },
    },
    esbuild: {
      minify: true,
      minifySyntax: true,
      minifyWhitespace: true,
      minifyIdentifiers: true,
      treeShaking: true,
      drop: ['console', 'debugger'],
      legalComments: 'none',
      banner: `/* 做政府放心、客户满意的中国最强最大充电网生态运营商 - 特来电 */`,
      footer: `/* 实现新能源车充新能源电，让尾气和雾霾远离人类 - 特来电 \n 打包时间：${new Date().toLocaleString()} */`,
    },
  };

  return mergeConfig(o, {
    ...other,
    define: {
      ...Object.fromEntries(
        Object.entries(other.define ?? {}).map(([k, v], i, a) => [
          k,
          JSON.stringify(v),
        ]),
      ),
    },
  });
};
